import { EditType } from '@/components/Editor/types';
import { Button, Modal, message } from 'antd';
import { useModel } from 'umi';
import { getBomResetData, setBomResetData } from './Reset';
import { setBomSaveLogData } from '../Log/Log';

export function Save() {
  const {
    plank,
    updatePlank,
    setPlank,
    getOldPlank,
    backLength,
    forwardLength,
  } = useModel('bom');
  async function onSave() {
    if (!plank) return;
    const resetData = await getBomResetData(plank.plankId);
    Modal.confirm({
      title: '确认保存吗？',
      onOk: async () => {
        try {
          if (!resetData) {
            await setBomResetData(getOldPlank(plank.plankId));
          }
          await updatePlank(plank, [
            EditType.Plank,
            EditType.Hole,
            EditType.Groove,
          ]);
          const { userId, userName } = await Manycore.User.getUserAsync();
          setBomSaveLogData({
            orderId: plank.orderId,
            detail: {
              userId: userId,
              userName: userName,
              modelId: plank.modelId,
              code: plank.code,
              name: plank.name,
              updateTime: new Date().getTime(),
            },
          });
        } catch (error) {
          if (error instanceof Error) {
            message.error(error.message);
          }
          return;
        }

        message.success('保存成功，物料数据已更新');
      },
    });
  }
  return (
    <>
      <Button
        disabled={backLength + forwardLength === 0}
        type="primary"
        onClick={onSave}
      >
        保存
      </Button>
    </>
  );
}
